/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.lavemylogic.friendsfinder.client.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.lavemylogic.friendsfinder.client.entity.Location;
import org.lavemylogic.friendsfinder.client.entity.User;
import org.lavemylogic.friendsfinder.client.entity.UserPK;
import org.lavemylogic.friendsfinder.client.exceptions.IllegalOrphanException;
import org.lavemylogic.friendsfinder.client.exceptions.NonexistentEntityException;
import org.lavemylogic.friendsfinder.client.exceptions.PreexistingEntityException;

/**
 *
 * @author Nj
 */
@SuppressWarnings("serial")
public class UserJpaController implements Serializable {

    public UserJpaController() {
    	emf = Persistence.createEntityManagerFactory("UserPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) throws PreexistingEntityException, Exception {
        if (user.getUserPK() == null) {
            user.setUserPK(new UserPK());
        }
        if (user.getLocationList() == null) {
            user.setLocationList(new ArrayList<Location>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Location> attachedLocationList = new ArrayList<Location>();
            for (Location locationListLocationToAttach : user.getLocationList()) {
                locationListLocationToAttach = em.getReference(locationListLocationToAttach.getClass(), locationListLocationToAttach.getLocationPK());
                attachedLocationList.add(locationListLocationToAttach);
            }
            user.setLocationList(attachedLocationList);
            em.persist(user);
            for (Location locationListLocation : user.getLocationList()) {
                User oldUserOfLocationListLocation = locationListLocation.getUser();
                locationListLocation.setUser(user);
                locationListLocation = em.merge(locationListLocation);
                if (oldUserOfLocationListLocation != null) {
                    oldUserOfLocationListLocation.getLocationList().remove(locationListLocation);
                    oldUserOfLocationListLocation = em.merge(oldUserOfLocationListLocation);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findUser(user.getUserPK()) != null) {
                throw new PreexistingEntityException("User " + user + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User persistentUser = em.find(User.class, user.getUserPK());
            List<Location> locationListOld = persistentUser.getLocationList();
            List<Location> locationListNew = user.getLocationList();
            List<String> illegalOrphanMessages = null;
            for (Location locationListOldLocation : locationListOld) {
                if (!locationListNew.contains(locationListOldLocation)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Location " + locationListOldLocation + " since its user field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Location> attachedLocationListNew = new ArrayList<Location>();
            for (Location locationListNewLocationToAttach : locationListNew) {
                locationListNewLocationToAttach = em.getReference(locationListNewLocationToAttach.getClass(), locationListNewLocationToAttach.getLocationPK());
                attachedLocationListNew.add(locationListNewLocationToAttach);
            }
            locationListNew = attachedLocationListNew;
            user.setLocationList(locationListNew);
            user = em.merge(user);
            for (Location locationListNewLocation : locationListNew) {
                if (!locationListOld.contains(locationListNewLocation)) {
                    User oldUserOfLocationListNewLocation = locationListNewLocation.getUser();
                    locationListNewLocation.setUser(user);
                    locationListNewLocation = em.merge(locationListNewLocation);
                    if (oldUserOfLocationListNewLocation != null && !oldUserOfLocationListNewLocation.equals(user)) {
                        oldUserOfLocationListNewLocation.getLocationList().remove(locationListNewLocation);
                        oldUserOfLocationListNewLocation = em.merge(oldUserOfLocationListNewLocation);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                UserPK id = user.getUserPK();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(UserPK id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getUserPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Location> locationListOrphanCheck = user.getLocationList();
            for (Location locationListOrphanCheckLocation : locationListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Location " + locationListOrphanCheckLocation + " in its locationList field has a non-nullable user field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(UserPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
